//
//  HUGroupViewModel.m
//  testMyPicturePicker
//
//  Created by Nova on 14-10-6.
//  Copyright (c) 2014年 huhuTec. All rights reserved.
//

#import "HUGroupViewModel.h"
#import "HUAssetsController.h"
#import "HUGroupCellViewModel.h"
@implementation HUGroupViewModel
- (id)init{
    self=[super init];
    if(self!=nil)
    {
        return self;
        
    }
    else
        return nil;
}

-(RACSignal*) getGroupData{
    RACSignal* sig=[RACSignal createSignal:^RACDisposable*(id<RACSubscriber> subcriber){
        ALAssetsLibraryGroupsEnumerationResultsBlock resultBlock=^(ALAssetsGroup* group,BOOL *stop){
            if(group)
            {
                //[group setAssetsFilter:self.assertsFilter];
                [subcriber sendNext:group];
            }
            else
                [subcriber sendCompleted];
        };
        
        ALAssetsLibraryAccessFailureBlock failureBlock = ^(NSError *error)
        {
            [subcriber sendError:error];
        };
        
        ALAssetsLibrary* library=[HUAssetsController defaultAssetsLibrary];
        
        //   [library enumerateGroupsWithTypes:ALAssetsGroupSavedPhotos usingBlock:resultBlock
        //                        failureBlock:failureBlock];
        //        
        //   NSUInteger type = ALAssetsGroupLibrary | ALAssetsGroupAlbum | ALAssetsGroupEvent |
        //    ALAssetsGroupFaces | ALAssetsGroupPhotoStream;
        
        [library enumerateGroupsWithTypes:ALAssetsGroupAll usingBlock:resultBlock
                             failureBlock:failureBlock];
        return nil;
    }]  ;
    
  RACSignal* sigTran= [[sig map:^(ALAssetsGroup* groupItem){
        CGImageRef posterImage      = groupItem.posterImage;
        size_t height               = CGImageGetHeight(posterImage);
        float scale                 = height /63.0;
        HUGroupCellViewModel* modelitem=[[HUGroupCellViewModel alloc] init];
        modelitem.groupImg      = [UIImage imageWithCGImage:posterImage scale:scale orientation:UIImageOrientationUp];
        modelitem.groupName         = [groupItem valueForProperty:ALAssetsGroupPropertyName];
        modelitem.groupQty=[NSString stringWithFormat:@"%ld", (long)groupItem.numberOfAssets];
        return modelitem;
  }] collect];
    
    NSNotificationCenter* notifyCenter=[NSNotificationCenter defaultCenter];
    RACSignal* ALAssetChange=[[notifyCenter rac_addObserverForName:ALAssetsLibraryChangedNotification object:nil] flattenMap:^(id _){
        return sigTran;
    }];
    return [[RACSignal merge:@[ALAssetChange,sigTran]] deliverOn:[RACScheduler mainThreadScheduler]];
    
    
}

@end
